/* framework.js - Core framework javascript and form submission handling */
var JS_STACK_INDEX = 0;
var JS_STACK = new Array;
var APPLICATION_LOADED = false;
var JQUERY_LOADED = false;
var LOCAL_STORAGE = 1;
window.LOCAL_STORAGE_STACK = 0;

var ajaxRequest = '';
var ajaxSuccessFailRequest = '';
var ajaxFormRunning = false;
var timeDiff = {
    setStartTime: function() {
        d = new Date();
        time = d.getTime();
    },
    getDiff: function() {
        d = new Date();
        return (d.getTime() - time);
    }
}

$(function() {
    timeDiff.setStartTime();
    load_jquery();
});


/* load all jQuery behaviours */
function load_jquery() {
    click($(".submit"), function($this) {
        $this.parents("form:first").submit();
        return false;
    });

    // Standard submit behaviour
    $("form").submit(function() {
        $(this).attr('change', '0');
        return true;
    });

    // All ajax forms behave the same, except the one with the 'notajax' class
    $("form").not(".not-ajax").off('submit').on('submit', function() {
        if (!ajaxFormRunning || $(this).hasClass('ajax-force')) {
            ajaxFormRunning = true;
            $('.tipsy').hide();
            display_loader_ajax($(this));
            var urlForm;
            if ($(this).attr('action').substr(0, 4) == 'Erra_' || $(this).attr('action').indexOf('http') == 0) {
                urlForm = $(this).attr('action');
            } else {
                urlForm = WEBROOT + '/POST_XMLHttpRequest/' + $(this).attr('action');
            }
            ajaxFormRequest = $(this).ajaxSubmit({
                url: urlForm,
                dataType: 'xml',
                success: function(data) {
                    POST_XMLHttpRequest(data);
                    remove_loader();
                }
            });
        }
        return false;
    });


    $("form.submit-on-change :input").each(function() {
        $(this).one('change', function() {
            $(this).parents("form").submit();
        });
    });

    $(":input").change(function() {
        $(this).parents("form").attr("change", 1);
    });

    // Autres functions à exécuter
    var len = JS_STACK.length;
    for (var i = 0; i < len; i++) {
        eval(JS_STACK[i]);
    }

    each($('.live-click'), function($this) {
        var functionName = $this.attr('data-function');
        if (functionName.length) {
            live($this, 'click', window[functionName]);
        }
    });

    each($('.live-change'), function($this) {
        var functionName = $this.attr('data-function');
        if (functionName.length) {
            live($this, 'change', window[functionName]);
        }
    });
    return false;
}

function preventAction(element) {
    element = (element==undefined) ? 'body' : element; 
    $(element).prepend('<div class="erra-form-common-popup_layer" id="pl_0"><div style="z-index: 1100;  -webkit-opacity: 0.05; -moz-opacity:0.05;  opacity: 0.05;filter:alpha(opacity=5); display: block; top:0px;" id="po_0" class="erra-form-common-popup_overlay"></div></div>');
} 

function allowAction() {
    $('.erra-form-common-popup_layer').remove();
} 

function erraShowSuccess(message) {
    if (message != undefined && message.length) {
        $('.ajax-config-validator span').html(message);
    }
    $('.ajax-config-validator').show();
}
function erraHideSuccess() {
    $('.ajax-config-validator').fadeOut(500);
}

function erraSuccess(message) {
    if (message != undefined && message.length) {
        $('.ajax-config-validator span').html(message);
    }
    $('.ajax-config-validator').show().delay(3000).fadeOut(500);
}


function erraError(message) {
    if (message != undefined && message.length) {
        $('.ajax-config-error span').html(message);
    }
    $('.ajax-config-error').show().delay(3000).fadeOut(500);
}



function ajax_form_reset($form) {
    if ($form.find('input:text, input:password, input:file, textarea').length)
        $form.find('input:text, input:password, input:file, textarea').val('');
    if ($form.find('select').removeAttr('selected').length)
        $form.find('select').removeAttr('selected').val('');

    if ($form.find('input:checkbox, input:radio').length)
        $form.find('input:checkbox, input:radio').removeAttr('checked');

    if ($form.find('.ajax-error-message').length)
        $form.find('.ajax-error-message').remove();
}

function stopAjax() {
    if (typeof ajaxRequest == 'object') {
        ajaxRequest.abort();
    }
    $('.ajax-config-loader').hide();
}

function ajax(url, post_array, success, doneFunction) {
    if (typeof ajaxRequest == 'object') {
        ajaxRequest.abort();
    }
    $('.ajax-config-loader').show();
    $('.ajax-config-loader-small').show();
    ajaxRequest = $.ajax({
        url: url,
        data: post_array,
        type: 'post',
        success: function(data) {
            $('.ajax-config-loader').hide();
            $('.ajax-config-loader-small').hide();
            success(data);
        }
    }).done(function() {
        if (typeof(doneFunction) == "function") {
            doneFunction();
        }
    });
}



function ajaxForce(url, post_array, success, doneFunction) {
    //$('.ajax-config-loader').show();
    $.ajax({
        url: url,
        data: post_array,
        type: 'post',
        success: function(data) {
            //$('.ajax-config-loader').hide();
            success(data);
        }
    }).done(function() {
        if (typeof(doneFunction) == "function") {
            doneFunction();
        }
    });
}

function ajaxSuccessFail(url, post_array, success, fail, doneFunction) {
    //$('.ajax-config-loader').show();
    if (typeof ajaxSuccessFailRequest == 'object') {
        ajaxSuccessFailRequest.abort();
    }
    // $('.ajax-config-loader').show(); 
    ajaxSuccessFailRequest = $.ajax({
        url: url,
        data: post_array,
        type: 'post',
        success: function(data) {
            //$('.ajax-config-loader').hide();
            success(data);
        },
        error: function(data) {
            fail(data);
        }
    }).done(function() {
        if (typeof(doneFunction) == "function") {
            doneFunction();
        }
    });
}

function bErrors(field_list) {
    var bErrorExist = false;
    for (var i = 0; i < field_list.length; i++) {
        if (field_list[i].data('bError') == true) {
            bErrorExist = true;
        }
    }
    return bErrorExist;
}

function setError($item, error_message) {
    removeError($item);
    $item.css('style', 'border: 1px solid red;');
    $item.before('<div class="erra-form-common-field_error">' + error_message + '</div>');

    $item.data('bError', true);
}

function removeError($element) {
    if ($element.length) {
        $element.removeAttr('style');
        if ($element.prev('div').hasClass('erra-form-common-field_error')) {
            $element.prev('div').remove();
        }
        $element.data('bError', false);
    }
}


function createPopup(data) {
    POPUP_COUNTER = parseInt(POPUP_COUNTER);
    $("body").prepend('<div id="pl_' + POPUP_COUNTER + '" class="erra-form-common-popup_layer"><div class="erra-form-common-popup_overlay" id="po_' + POPUP_COUNTER + '" style="z-index:' + (1000 + POPUP_COUNTER * 2) + ';"></div><div id="pw_' + POPUP_COUNTER + '" class="erra-form-common-popup_window" style="z-index:' + (1001 + POPUP_COUNTER * 2) + ';"></div></div>');

    $("#po_" + POPUP_COUNTER).css('opacity', 0.65);
    $("#po_" + POPUP_COUNTER).css('display', 'block');
    $("#pw_" + POPUP_COUNTER).html(data);
    $("#pw_" + POPUP_COUNTER).show();
    popup_dimensions(POPUP_COUNTER);
    load_jquery();
    remove_loader();
    POPUP_COUNTER += 1;
}

function closePopup(object, confirm) {
    // TODO : Agenda can't be ajax

    if ($('#calendar').length) {
        //$('#calendar').weekCalendar("refresh"); 
        if ($('.wc-time:not([data-event-id])').length) {
            $('.wc-time:not([data-event-id])').each(function() {
                $(this).parents('.wc-cal-event:first').remove();
            });
        }
    }
    $('form[action="Erra_System_Action/refreshList"]').submit();

    if (object == undefined || object == null) {
        var i = $(".erra-form-common-popup_layer").length - 1;
        var $e = $('#pl_' + i); // Get nearest popup
        var changes = false;
        $e.find("form").each(function() {
            if ($e.attr("change") == 1) {
                changes = true;
            }
        });
        // Refresh parent list if exists
        var objectHash = $e.find('div[id^="EDIT_IN_PLACE"]').attr('data-object');
        var potentialParentList = $('div[id^="FIELD_LIST_"][data-object="' + objectHash + '"]');
        if (potentialParentList.length) {
            potentialParentList.find('form[action="Erra_System_Action/refreshList"]').addClass('ajax-force').submit();
        }

        if (confirm == false) {
            $e.remove();
            POPUP_COUNTER -= 1;
            popup_dimensions();
        }
    } else {
        $(object).parents(".erra-form-common-popup_layer:first").each(function() {
            var changes = false;
            $(this).find("form").each(function() {
                if ($(this).attr("change") == 1) {
                    changes = true;
                }
            });
            if (confirm == false) {
                $(this).remove();
                POPUP_COUNTER -= 1;
                popup_dimensions();
            }

            // Refresh parent list if exists
            var objectHash = $(this).find('div[id^="EDIT_IN_PLACE"]').attr('data-object');
            var potentialParentList = $('div[id^="FIELD_LIST_"][data-object="' + objectHash + '"]');
            if (potentialParentList.length) {
                potentialParentList.find('form[action="Erra_System_Action/refreshList"]').submit();
            }
        });
    }
    if (POPUP_COUNTER < 0) {
        POPUP_COUNTER = 0;
    }
}

function popup_dimensions(i) {
    if (i == undefined) {
        i = POPUP_COUNTER - 1;
    }
    if (i < 0) {
        return;
    }

    var margin = 50;
    var mh = $(window).height() - (margin * 2);

    if (!$.browser.msie) {
        $("#pw_" + i).css("opacity", 0);
    }

    $("#pw_" + i + " .c>div").css("overflow-y", 'auto');
    $("#pw_" + i + " .c>div").css("overflow-x", 'visible');

    $("#pw_" + i + " >div").css("max-height", mh);
    $("#pw_" + i).css("left", ($(window).width() - $("#pw_" + i).width()) / 2);
    if ($("#pw_" + i + " .c>div").attr('top')) {
        $("#pw_" + i).css("top", parseInt($("#pw_" + i + " .c>div").attr('top')));
    } else {
        var top = (mh - $("#pw_" + i).height()) / 2 + margin;
        top = '20';
        $("#pw_" + i).css("top", top);
    }
    if (!$.browser.msie) {
        $("#pw_" + i).css("opacity", 1);
    }
}

function changepopup(data) {
    var pc = POPUP_COUNTER - 1;
    $("#pw_" + pc).html(data);
    popup_dimensions(pc);
}


function isSet(i) {
    return (i == null || i == 'null' || i == '' || i == 'undefined');
}


function POST_XMLHttpRequest(data, reload) {

    var error = new Array();
    var confirmation = '';
    var ok = true;

    var t = $(data).children('rsp').children().get();
    for (var i = 0; i < t.length; i++) {
        var e = t[i];
        var name = e.nodeName;

        if (name == 'confirmation') {
            var contentconfirm = $(e).text();
            confirmation += "<p>" + contentconfirm + "</p>";
        } else if (name == 'error') {
            var errors = $(e).children().get();
            for (var j = 0; j < errors.length; j++) {
                var err = errors[j];
                var ename = err.nodeName;
                var econtent = $(err).text();
                $("#" + ename).addClass('error');
                $("#" + ename).val('');
                error.push(econtent);
                ok = false;
            }
        } else if (name == 'content') {
            $(e).children().each(function() {
                var cname = $(this).attr('selector');
                var ccontent = $(this).text();
                if (ccontent == '') {
                    $(getSelector(cname)).html(ccontent);
                } else {

                    $(getSelector(cname)).html(ccontent);
                }
                if (POPUP_COUNTER - 1 >= 0) {
                    popup_dimensions(POPUP_COUNTER - 1);
                }
            });
        } else if (name == 'replace') {
            $(e).children().each(function() {
                var cname = $(this).attr('selector');
                var ccontent = $(this).text();
                if (ccontent == '') {
                    $(getSelector(cname)).replaceWith(ccontent);
                } else {
                    $(getSelector(cname)).replaceWith(ccontent);
                }
                if (POPUP_COUNTER - 1 >= 0) {
                    popup_dimensions(POPUP_COUNTER - 1);
                }
            });
        } else if (name == 'append') {
            var contents = $(e).children().get();
            for (var k = 0; k < contents.length; k++) {
                var content = contents[k];
                var cname = content.nodeName;
                var ccontent = $(content).text();
                if (ccontent == '') {
                    $(getSelector(cname)).append(ccontent);
                } else {
                    $(getSelector(cname)).append(ccontent);
                }
                if (POPUP_COUNTER - 1 >= 0) {
                    popup_dimensions(POPUP_COUNTER - 1);
                }
            }
        } else if (name == 'param') {
            var ids = $(e).children().get();
            for (var p = 0; p < ids.length; p++) {
                var id = ids[p];
                var idname = id.nodeName;
                var params = $(id).children().get();
                var o = {};
                for (var q = 0; q < params.length; q++) {
                    var param = params[q];
                    var paramname = param.nodeName;
                    var paramcontent = $(param).text();
                    o[paramname] = paramcontent;
                }
                $("#" + idname).attr(o);
                $("#" + idname).parents("form").unbind('submit');
            }
        } else if (name == 'alert') {
            var alerts = $(e).children().get();
            for (var r = 0; r < alerts.length; r++) {
                var alert = alerts[r];
                var acontent = $(alert).text();
                //window.alert(acontent);
            }


        } else if (name == 'ok') {
            var oks = $(e).children().get();
            for (var l = 0; l < oks.length; l++) {
                var ok = oks[l];
                var oname = ok.nodeName.toLowerCase();
                $("#" + oname).removeClass('error');
            }
        } else if (name == 'redirection') {
            var url = $(e).text();
            window.location = url;
        } else if (name == 'show') {
            var oks = $(e).children().get();
            for (var l = 0; l < oks.length; l++) {
                var ok = oks[l];
                var oname = ok.nodeName;
                $("#" + oname).show('fast');
            }
        } else if (name == 'debug') {
            // Do nothing
        } else if (name == 'eval') {
            var codes = $(e).children().get();
            for (var r = 0; r < codes.length; r++) {
                var code = codes[r];
                eval($(code).text());
            }
        } else if (name == 'closepopup') {
            closePopup(null, false);
            var codes = $(e).children().get();
            for (var r = 0; r < codes.length; r++) {
                var code = codes[r];
                eval($(code).text());
            }
        } else if (name == 'openpopup') {
            var opens = $(e).children().get();
            for (var op = 0; op < opens.length; op++) {
                var cont = opens[op];
                createPopup($(cont).text());
            }
        } else if (name == 'changepopup') {
            var changes = $(e).children().get();
            for (var cp = 0; cp < changes.length; cp++) {
                var cont = changes[cp];
                changepopup($(cont).text());

            }
        }
        else if (name == 'popupdimensions') {
            popup_dimensions();
        } else if (name == 'timer') {
            var time = parseInt($(e).text());
            var t = setTimeout("doNothing()", time);
        } else if (name == 'value') {
            var values = $(e).children().get();
            for (var v = 0; v < values.length; v++) {
                var node = values[v];
                var oname = node.nodeName;
                var val = $("#" + oname).val($(node).text());
            }
        }
    }

    if (error.length > 0) {
        $("#message").html(error.join('<br />'));
    }

    if (confirmation != '') {
        $("#confirmation").html(confirmation);
        $("#confirmation").animate({
            height: 26,
            opacity: 1
        }, 2000, function() {
            $("#confirmation").fadeTo(10000, 1, function() {
                $("#confirmation").animate({
                    height: 0,
                    opacity: 0
                }, 2000);
                $("#confirmation").empty();
            });
        });
    }
    if (reload == true || reload == undefined) {
        load_jquery();
        ui_boot_dynamic();
        load_application();

    }
    ajaxFormRunning = false;
    return ok;
}

/**
 *
 * @access public
 * @return void
 **/
function getSelector(name) {
    if (name.substr(0, 1) == '#' || name.substr(0, 1) == '.') {
        return name;
    } else {
        return "#" + name;

    }
}

function doNothing() {

}

function display_loader_ajax(element) {
    // TODO: include a FORCED way to set #erra-loader-section as the main site loading event
    var $loadingContent = $('#erra-loader-section').find('.loading_content');

    if (element.parents('div[role="dialog"]:first').length > 0 && element.parents('div[role="dialog"]:first').attr('data-message')) {
        $loadingContent.html(element.parents('div[role="dialog"]:first').attr('data-message'));
    } else {
        $loadingContent.html($('#erra-loader-section').attr('data-message'));
    }
    $('#erra-loader-section').show();

}

function remove_loader() {
    $('#erra-loader-section').fadeOut();
}

function start_loading(loadingMessage, showImage) {
    var $loadingContent = $('#erra-loader-section').find('.loading_content');
    var $loadingImage = $('#erra-loader-section').find('img');
    if (showImage != undefined && showImage == false && $loadingImage.length) {
        $('#erra-loader-section').find('img').hide();
    } else if ($loadingImage.length) {
        $('#erra-loader-section').find('img').show();
    }
    $loadingContent.html(loadingMessage);
    $('#erra-loader-section').show();

}

function end_loading() {
    remove_loader();
}

function live($item, eventName, exec) {
    $item.on(eventName, function(event) {
        var id_defined = ($item.attr('id') == undefined) ? false : true;
        if (event.handled !== true && id_defined == true)
        {
            exec($(this));
            event.handled = true;
        }
        return false;
    });
}

function click($item, exec) {
    if ($item.length) {
        $item.off('click').on('click', function(e) {
            exec($(this));
        });
    }
    return false;
}

function each($collection, exec) {
    if ($collection.length) {
        for (var i = 0, len = $collection.length; i < len; i++) {
            exec($($collection[i]));
        }
    }
}


function _live(item, eventName, exec) {
    item.on(eventName, function(event) {
        //FIXME : WTF WITH LIVE ?
        if (event.handled !== true)
        {
            exec($(this));
            event.handled = true;
        }
        return false;
    });
}

function ajax_navigation() {
    var hashIdentifier = window.location.hash;
    if (hashIdentifier != undefined && hashIdentifier.length > 3 && hashIdentifier.indexOf('#!/') == 0) {
        var urlContent = hashIdentifier.substr(2, hashIdentifier.length);
        if (urlContent != undefined && urlContent.length > 0 && window.location.hash.indexOf(hashIdentifier) > -1) {
            var contentHref = window.location.hash;
            contentHref = contentHref.replace('#!', '');
            if (urlContent.indexOf('http://') == -1) {
                contentHref = WEBROOT + '/ajaxcontent/' + LANG + contentHref;
            }
            $('#erra-loader-section').find('.loading_content').html($('#erra-loader-section').attr('data-message'));
            $('#erra-loader-section').show();
            $.ajax(contentHref).done(function(data) {
                var $data = $('<div>' + data + '</div>');
                // Load javascript files dynamically
                // Load javascript files dynamically
                // This way, <view-script> can be root or n-depth element
                var startIndex = 0;
                var jsCount = 0;
                while (data.indexOf('<view-script src="', startIndex) >= 0) {
                    startIndex = data.indexOf('<view-script src="', startIndex) + 18;
                    endIndex = data.indexOf('"', startIndex);
                    var scriptSrc = data.substring(startIndex, endIndex);
                    if (scriptSrc.length && scriptSrc.indexOf('.js') > 0) {
                        $.getScript(scriptSrc);
                    }
                    jsCount++;
                    if (jsCount > 10) {
                        break;
                    }
                }
                /*
                 *TODO : FIX FOR EVERY BROTHERS WITH REGEXP
                 */
                $data.find('ajax-script').each(function() {
                    if ($(this).attr('src').length) {
                        $.getScript($(this).attr('src'));
                        $(this).remove();
                    }
                });
                $('#erra-loader-section').slideDown();
                $data.find('.erra-region').each(function() {
                    update_region('#' + $(this).attr('id'), data);
                });
                $('#erra-loader-section').hide();
                return false;
            });
        }
    }
    return false;
}


function update_region(region_name, data) {
    var region_contents = $('<div>' + data + '</div>').find(region_name).html();
    if (region_contents != null) {
        $(region_name).hide(0, function() {
            $(this).html(region_contents);
            $(this).fadeIn(1000, function() {
                load_jquery();
                ui_boot_dynamic();
                load_application();
            });

        });
    }
    return false;
}


function searchCleanText(elementToClear) {
    var $searchElement = $(elementToClear.attr('data-clear-id'));
    if ($searchElement.length) {
        $searchElement.val('');
        $searchElement.parents('form:first').submit();
    }
}

function restHandle(data) {
    if (data.length >= 4 && parseInt(data.substring(0, 3)) > 0 && data.charAt(3) == '§') {
        var code = parseInt(data.substring(0, 3));
        // TODO : stylize depending rest code type
        result = (data.substring(4, data.length));
        if (result.charAt(result.length - 1) == '§') {
            return result.substring(0, result.length - 2);
        } else {
            return result.substring(0, result.length - 1);
        }
    }
    return data;
}

function getRest(data) {
    if (data != undefined) {
        if (data.length >= 4 && parseInt(data.substring(0, 3)) > 0 && data.charAt(3) == '§') {
            var code = parseInt(data.substring(0, 3));
            data = data.replace(code + '§', '');
            var message = (data.substring(0, data.indexOf('§')));
            message = message.replace('§', '');
            return {
                'code': parseInt(code),
                'message': message
            };
        }
    }
    return {
        'code': 0,
        'message': ''
    };
}

function getResponse(data) {
    if (data != undefined) {
        if (data.length >= 4 && parseInt(data.substring(0, 3)) > 0 && data.charAt(3) == '§') {
            var code = parseInt(data.substring(0, 3));
            data = data.replace(code + '§', '');
            var message = (data.indexOf('§') + 1 < data.length) ? (data.substring(data.indexOf('§') + 1, data.length)) : '';
            return message;
        }
    }
    return '';
}
